package cn.springcloud.alibaba.security.handler;

import cn.springcloud.alibaba.core.util.ResponseUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

	public final void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
		log.error(e.getMessage(), e);

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("code", 401);

		Throwable cause = e.getCause();
		if (cause instanceof InsufficientAuthenticationException) {
			Throwable cause2 = cause.getCause();
			if (cause2 instanceof InvalidTokenException) {
				resultMap.put("message", "认证失败,无效或过期token");
			}
		} else if (cause instanceof InvalidTokenException) {
			resultMap.put("message", "认证失败,无效或过期token");
		} else {
			resultMap.put("message", "认证失败,没有携带token");
		}

		ResponseUtil.outputJsonResponse(response, resultMap);
	}
}
